package lingnan.cn.edu.util;

import java.util.HashMap;
import java.util.Map;

import lingnan.cn.edu.User.Product;

public class ShoppingCar {
	public Integer totalPrice=0;
	public Integer totalCount=0;
	public Map<Integer,CarItem> container = new HashMap<Integer,CarItem>();
		
	
	//创建一个Map类型的容器，  根据对应的Key(Product.ID)来获取对应的值(CarItem);
	
	//第一步
 
	
	
    //增加商品
	public void add(Product product) {
		
		CarItem carItem = container.get(product.getId()); 
		//CarItem == 容器获取的key, (key--value)   创建一个映射关系(Id--CarItem)  可能存在也可能不存在。
		
		if(carItem==null) {      //购物车中无此商品
			carItem = new CarItem();
			carItem.setProduct(product);           
			
			carItem.setCount(1);
			carItem.setItemPrice(product.getPrice());
			totalPrice=totalPrice+product.getPrice();
			totalCount=totalCount+1;
			container.put(product.getId(),carItem);
		}else {
			carItem.setCount(carItem.getCount()+1);//购物车中已有商品
			carItem.setItemPrice(product.getPrice()*carItem.getCount());
			totalPrice=totalPrice+product.getPrice();
			totalCount=totalCount+1;
		}
		
	}
	
	
	
	//删除。。。。
	public void delete(Product product) {//TODO  product ?
		CarItem carItem = container.get(product.getId());
		if(carItem!=null) {
			if(carItem.getCount()==1) {
				container.remove(product.getId());
				totalPrice=totalPrice-product.getPrice();
				totalCount=totalCount-1;
			}else {
			    carItem.setCount(carItem.getCount()-1);
			    carItem.setItemPrice(carItem.getCount()*product.getPrice());
			    totalPrice=totalPrice-product.getPrice();
			    totalCount=totalCount-1;
			}
				
			
		}
	}
	
	
	
	
	//清空购物车
	public void clear() {
		container.clear();
		totalPrice=0;
		totalCount=0;
		
	}
	
	
	//购物车中加或减
	public void add1(int id) {
		CarItem carItem = container.get(id);
		carItem.setCount(carItem.getCount()+1);//购物车中已有商品
		carItem.setItemPrice(carItem.getProduct().getPrice()*carItem.getCount());
		totalPrice=totalPrice+carItem.getProduct().getPrice();
		totalCount=totalCount+1;
	}
	
	public void delete1(int id) {
		CarItem carItem = container.get(id);
		if(carItem.getCount()==1) {
			container.remove(carItem.getProduct().getId());
			totalPrice=totalPrice-carItem.getProduct().getPrice();
			totalCount=totalCount-1;
		}else {
		    carItem.setCount(carItem.getCount()-1);
		    carItem.setItemPrice(carItem.getCount()*carItem.getProduct().getPrice());
		    totalPrice=totalPrice-carItem.getProduct().getPrice();
		    totalCount=totalCount-1;
		}
	}
}
